package com.yanx.common.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;

import java.util.LinkedList;
import java.util.List;

/**
 * 字符串工具
 * 基于Hutool
 *
 * @author gotanks
 * @version 1.0
 * @since 2020-05-13
 */
public final class String_ extends StrUtil {

    /**
     * 批量去掉指定后缀
     *
     * @param str    字符串
     * @param suffix 后缀
     * @return 切掉后的字符串，若后缀不是 suffix， 返回原字符串
     */
    public static String removeSuffix(CharSequence str, CharSequence... suffix) {
        if (suffix == null) {
            return null;
        }
        for (int i = 0; i < suffix.length; i++) {
            str = removeSuffix(str, suffix[i]);
        }
        return str.toString();
    }

    /**
     * 截取指定字符串多段中间部分，不包括标识字符串<br>
     * <p>
     * 栗子：
     *
     * <pre>
     * StrUtil.subBetweenAll(null, *)          			= []
     * StrUtil.subBetweenAll(*, null)          			= []
     * StrUtil.subBetweenAll(*, *)          			= []
     * StrUtil.subBetweenAll("", "")          			= []
     * StrUtil.subBetweenAll("", "#")         			= []
     * StrUtil.subBetweenAll("gotanks", "")     		= []
     * StrUtil.subBetweenAll("#gotanks#", "#")   		= ["gotanks"]
     * StrUtil.subBetweenAll("#hello# #world#!", "#")   = ["hello", "world"]
     * StrUtil.subBetweenAll("#hello# world#!", "#");   = ["hello"]
     * </pre>
     *
     * @param str            被切割的字符串
     * @param beforeAndAfter 截取开始和结束的字符串标识
     * @return 截取后的字符串
     * @author gotanks
     * @since 5.4.7
     */
    public static String[] subBetweenAll(CharSequence str, CharSequence beforeAndAfter) {
        String[] resultArr = new String[0];
        if (hasEmpty(str, beforeAndAfter) || !contains(str, beforeAndAfter)) {
            return resultArr;
        }

        final List<String> result = new LinkedList<>();
        String[] split = splitToArray(str, beforeAndAfter);
        for (int i = 1, length = split.length - 1; i < length; i = i + 2) {
            result.add(split[i]);
        }
        return result.toArray(resultArr);
    }

    /**
     * 截取部分字符串，这里一个汉字的长度认为是3
     *
     * @param str 字符串
     * @return 切割后的字符串
     */
    public static String subPreUTF8(CharSequence str, int len, CharSequence suffix) {

        if (isEmpty(str)) {
            return str(str);
        }

        byte[] b;
        int counterOfDoubleByte = 0;
        b = str.toString().getBytes(CharsetUtil.CHARSET_UTF_8);
        if (b.length <= len) {
            return str.toString();
        }
        for (int i = 0; i < len; i++) {
            if (b[i] < 0) {
                counterOfDoubleByte++;
            }
        }

        if (counterOfDoubleByte % 3 != 0) {
            len += 1;
        }
        return new String(b, 0, len, CharsetUtil.CHARSET_UTF_8) + suffix;
    }
}
